package com.ct.application.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ct.application.system.model.po.AdminSystemSavePO;
import com.ct.application.system.model.po.AdminSystemSearchPO;
import com.ct.application.system.model.vo.AdminSystemLoginVO;
import com.ct.application.system.model.vo.AdminSystemVO;
import com.ct.application.system.service.IAdminSystemService;
import com.ct.application.sysuser.contants.SysUserContants;
import com.ct.redis.util.RedisUtil;
import com.ct.repository.convert.CopyConvertUtils;
import com.ct.system.enums.SystemResultEnum;
import com.ct.system.orm.AdminSystem;
import com.ct.system.responsity.admin.IAdminSystemRepository;
import com.ct.system.responsity.admin.IAdminSystemUserRepository;
import com.ct.utils.exception.ApiException;
import com.ct.utils.jwt.JwtUtil;
import com.ct.utils.jwt.UserInfo;
import com.ct.utils.threadlocal.UserThreadLocal;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 文章表 服务实现类
 * </p>
 *
 * @author Auto Generator
 * @since 2023-08-16
 */
@Service
public class AdminSystemService  implements IAdminSystemService {

    @Autowired
    private IAdminSystemRepository adminSystemRepository;
    @Autowired
    private IAdminSystemUserRepository adminSystemUserRepository;
    @Resource
    private RedisUtil<String> redisUtil;

    @Override
    public Page<AdminSystemVO> findAdminSystem(AdminSystemSearchPO adminSystemSearchPO) {
        LambdaQueryWrapper<AdminSystem> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Objects.nonNull(adminSystemSearchPO.getStatus()),AdminSystem::getStatus,adminSystemSearchPO.getStatus());
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(adminSystemSearchPO.getKeyword()), AdminSystem::getSysname, adminSystemSearchPO.getKeyword());
        lambdaQueryWrapper.orderByDesc(AdminSystem::getCreateTime);
        // 查询返回
        Page<AdminSystem> page = new Page<>(adminSystemSearchPO.getPageNo(), adminSystemSearchPO.getPageSize());
        return adminSystemRepository.tranferPageBo(adminSystemRepository.page(page,lambdaQueryWrapper),AdminSystemVO.class);
    }



    @Override
    public Page<AdminSystemVO> findAdminSystemBind(AdminSystemSearchPO adminSystemSearchPO) {
        LambdaQueryWrapper<AdminSystem> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Objects.nonNull(adminSystemSearchPO.getStatus()),AdminSystem::getStatus,adminSystemSearchPO.getStatus());
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(adminSystemSearchPO.getKeyword()), AdminSystem::getSysname, adminSystemSearchPO.getKeyword());
        lambdaQueryWrapper.orderByDesc(AdminSystem::getCreateTime);
        // 查询返回
        Page<AdminSystem> page = new Page<>(adminSystemSearchPO.getPageNo(), adminSystemSearchPO.getPageSize());
        Page<AdminSystemVO> adminSystemVOPage = adminSystemRepository.tranferPageBo(adminSystemRepository.page(page, lambdaQueryWrapper), AdminSystemVO.class);
        if(adminSystemSearchPO.getUserId()!=null) {
            List<AdminSystemVO> records = adminSystemVOPage.getRecords();
            if(CollectionUtils.isNotEmpty(records)){
                // 查询用户绑定的系统
                List<AdminSystem> adminSystemAll = adminSystemUserRepository.findAdminSystemAll(adminSystemSearchPO.getUserId());
                if (CollectionUtils.isNotEmpty(adminSystemAll)) {
                    List<Long> bindSystemIds = adminSystemAll.stream().map(AdminSystem::getId).collect(Collectors.toList());
                    List<AdminSystemVO> collect = records.stream().map(c -> {
                        long count = bindSystemIds.stream().filter(cc -> cc.equals(c.getId())).count();
                        c.setBindFlag(count>0);
                        return c;
                    }).collect(Collectors.toList());
                    adminSystemVOPage.setRecords(collect);
                }
            }
        }

        return adminSystemVOPage;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveUpdateAdminSystem(AdminSystemSavePO adminSystemSavePO) {
        AdminSystem adminSystem = CopyConvertUtils.copyProperties(adminSystemSavePO, AdminSystem.class);
        boolean b = adminSystemRepository.saveOrUpdate(adminSystem);
        return b;
    }

    @Override
    public boolean deleteAdminSystemById(Long id) {
        boolean b1 = adminSystemUserRepository.countSystemId(id);
        if(b1){
            throw new ApiException(SystemResultEnum.SYSTEM_BIND_EX);
        }
        boolean b =  adminSystemRepository.removeById(id);
        return b;
    }

    @Override
    public AdminSystemVO getAdminSystemById(Long id) {
        return adminSystemRepository.tranferBo(adminSystemRepository.getById(id),AdminSystemVO.class);
    }

    // 状态修改
    @Override
    public boolean updateStatus(Long id,String column,Integer value){
        boolean b =  adminSystemRepository.updateStatus(id,column,value);
        return b;
    }

    @Override
    public boolean updateStatusStr(Long id,String column,String value){
        boolean b =  adminSystemRepository.updateStatusStr(id,column,value);
        return b;
    }


    /**
     * 系统切换
     * @param adminSystemLoginVO
     * @return
     */
    @Override
    public String systemChange(AdminSystemLoginVO adminSystemLoginVO){
        UserInfo userInfo = UserThreadLocal.get();
        userInfo.setSystemId(adminSystemLoginVO.getId());
        userInfo.setSystemName(adminSystemLoginVO.getSysname());
        userInfo.setAppid(adminSystemLoginVO.getSyscode());
        Map<String, String> map = JwtUtil.generateToken(userInfo);
        // 创建token
        String token = map.get("token");
        // 要把token放入到redis---挤下线
        redisUtil.set(SysUserContants.LOGIN_REDIS_TOKEN_KEY + userInfo.getId(), token, JwtUtil.EXPIRE_TIME, TimeUnit.MILLISECONDS);
        return token;
    }
}
